import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/userStore';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/index.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/register/index.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/',
      name: 'admin',
      component: () => import('../views/admin/index.vue'),
      meta: { requiresAuth: true },
      redirect: '/permission',
      children: [
        {
          path: 'user',
          name: 'user',
          component: () => import('../views/admin/user/index.vue'),
        },
        {
          path: 'role',
          name: 'role',
          component: () => import('../views/admin/role/index.vue'),
        },
        {
          path: 'permission',
          name: 'permission',
          component: () => import('../views/admin/permission/index.vue'),
        },
        {
          path: 'product',
          name: 'product',
          component: () => import('../views/admin/product/index.vue'),
        },
        {
          path: 'category',
          name: 'category',
          component: () => import('../views/admin/category/index.vue'),
        },
        {
          path: 'order',
          name: 'order',
          component: () => import('../views/admin/order/index.vue'),
        },
      ],
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('../views/error/404.vue'),
      meta: { requiresAuth: false },
    },
  ],
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const isAuthenticated = userStore.token;

  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'login' });
  } else {
    next();
  }
});

export default router;
